import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutterapp/models/general_type.dart';
import 'package:flutterapp/page/home/tab_search/filter_bar/item.dart';
import 'package:flutterapp/page/utils/common_picker/index.dart';
import 'package:flutterapp/page/utils/dio_http.dart';
import 'package:flutterapp/page/utils/scopoed_model_helper.dart';
import 'package:flutterapp/scoped_model/room_filter.dart';

import 'data.dart';

String lastCityId;

class FilterBar extends StatefulWidget {
  final ValueChanged<FilterBarResult> onChange;

  const FilterBar({Key key, this.onChange}) : super(key: key);

  @override
  _FilterBarState createState() => _FilterBarState();
}

class _FilterBarState extends State<FilterBar> {
  List<GeneralType> areaList = [];
  List<GeneralType> priceListList = [];
  List<GeneralType> rentTypeList = [];
  List<GeneralType> roomTypeList = [];
  List<GeneralType> orientedList = [];

  List<GeneralType> floorList = [];
  bool isAreaActive = false;
  bool isRentTypeActive = false;
  bool isPriceActive = false;
  bool isFilterActive = false;

  String areaId = '';
  String rentTypeId = '';
  String priceId = '';
  String filterId = '';
  List<String> moreIds = [];

  //统一组件
  _onPublicChange(int bool, BuildContext context, List<GeneralType> dataList) {
    //调用组件
    var result = CommonPicker.showPicker(
      context: context,
      value: 0,
      options: dataList.map((e) => e.name).toList(),
    );

    //获取返回值
    result.then((index) {
      if (index == null) return;
      setState(() {
        areaId = areaList[index].id;
      });
      _onChange();
    }).whenComplete(() async {
      isAreaActive = false;

      setState(() {
        switch (bool) {
          case 1:
            isAreaActive = false;

            break;
          case 2:
            isRentTypeActive = false;

            break;
          case 3:
            isPriceActive = false;

            break;
          case 4:
            isFilterActive = false;

            break;
          default:
            break;
        }
      });
    });
  }
  //-----------------------

  _onAreaChange(context) {
    setState(() {
      isAreaActive = true;
    });

    //调用组件
    var result = CommonPicker.showPicker(
      context: context,
      value: 0,
      options: areaList.map((e) => e.name).toList(),
    );

    //获取返回值
    result.then((index) {
      if (index == null) return;
      setState(() {
        areaId = areaList[index].id;
      });
      _onChange();
    }).whenComplete(() => {isAreaActive = false});
    // _onPublicChange(1, context, areaList);
  }

  _onRentTypeChange(context) {
    setState(() {
      isRentTypeActive = true;
    });
    //调用组件
    var result = CommonPicker.showPicker(
      context: context,
      value: 0,
      options: rentTypeList.map((e) => e.name).toList(),
    );

    //获取返回值
    result.then((index) {
      if (index == null) return;
      setState(() {
        rentTypeId = rentTypeList[index].id;
      });
      _onChange();
    }).whenComplete(() => {isRentTypeActive = false});
    //_onPublicChange(2, context, rentTypeList);
  }

  _onPriceChange(context) {
    setState(() {
      isPriceActive = true;
    });
    //调用组件
    var result = CommonPicker.showPicker(
      context: context,
      value: 0,
      options: priceListList.map((e) => e.name).toList(),
    );

    //获取返回值
    result.then((index) {
      if (index == null) return;
      setState(() {
        priceId = priceListList[index].id;
      });
      _onChange();
    }).whenComplete(() => {isPriceActive = false});
    //_onPublicChange(3, context, priceListList);
  }

  _onFilterChange(context) {
    Scaffold.of(context).openEndDrawer();

    //调用组件
    //_onPublicChange(4, context, null);
  }

  _onChange() {
    //把数据set进去
    var selectedList =
        ScopedModelHelper.getModel<FilterBarModel>(context).selectedList;
    if (widget.onChange != null) {
      //传数据到外层
      widget.onChange(FilterBarResult(
          areaId: areaId,
          priceId: priceId,
          rentTypeId: rentTypeId,
          moreIds: selectedList.toList()));
    }
  }

  _getData() async {
    //初始化的时候发送请求
    var cityId = ScopedModelHelper.getAreaId(context);
    lastCityId = cityId;
    print('++++++++++++++++++++++++++++++++');
    print(cityId);
    //restfull 风格
    var url = '/houses/conditin/${cityId}';

    //发送请求
    var res = await DioHttp.of(context).get(url);
    var data = json.decode(res.toString())['body'];
    //判断组件卸载的时候是否接受到网络请求
    if (!this.mounted) {
      return;
    }
    //print(data['area']);
    //print(data['priceList']);
    //print(data['rentType']);
    //print(data['roomType']);
    print(data['oriented']);
    //print(data['floor']);

    List<GeneralType> areaList = List<GeneralType>.from(
        data['area'].map((item) => GeneralType.fromJson(item)).toList());

    List<GeneralType> priceListList = List<GeneralType>.from(
        data['priceList'].map((item) => GeneralType.fromJson(item)).toList());

    List<GeneralType> rentTypeList = List<GeneralType>.from(
        data['rentType'].map((item) => GeneralType.fromJson(item)).toList());

    List<GeneralType> roomTypeList = List<GeneralType>.from(
        data['roomType'].map((item) => GeneralType.fromJson(item)).toList());

    List<GeneralType> orientedList = List<GeneralType>.from(
        data['oriented'].map((item) => GeneralType.fromJson(item)).toList());

    List<GeneralType> floorList = List<GeneralType>.from(
        data['floor'].map((item) => GeneralType.fromJson(item)).toList());

    setState(() {
      this.areaList = areaList;
      this.priceListList = priceListList;
      this.rentTypeList = rentTypeList;
      this.roomTypeList = roomTypeList;
      this.orientedList = orientedList;
      this.floorList = floorList;
    });

    //创建一个Map 并给状态赋值
    Map<String, List<GeneralType>> dataList = Map<String, List<GeneralType>>();
    dataList['roomTypeList'] = this.roomTypeList;
    dataList['orientedList'] = this.orientedList;
    dataList['floorList'] = this.floorList;
    ScopedModelHelper.getModel<FilterBarModel>(context).dataList = dataList;
  }

  //初始化的时候使用
  @override
  void initState() {
    //设置延迟执行
    Timer.run(_getData);
    // TODO: implement initState
    super.initState();
  }

  //获取selectedList
  @override
  void didChangeDependencies() {
    _onChange();
    // TODO: implement didChangeDependencies
    //解决城市变更获取不到id的判断
    if (lastCityId != null &&
        ScopedModelHelper.getAreaId(context) != lastCityId) {
      _getData();
    }
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      //margin: EdgeInsets.only(left: 20.0, right: 20.0),
      height: 41.0,
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Colors.black12, width: 1.0),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Item(title: '区域', isActive: isAreaActive, onTap: _onAreaChange),
          Item(
              title: '方式',
              isActive: isRentTypeActive,
              onTap: _onRentTypeChange),
          Item(title: '租金', isActive: isPriceActive, onTap: _onPriceChange),
          Item(title: '筛选', isActive: isFilterActive, onTap: _onFilterChange),
        ],
      ),
    );
  }
}
